const http = require('http');
const { ApolloServer, PubSub } = require('apollo-server-koa');
const pubsub = new PubSub();
const typeDefs = require('./type-defs');


const POST_ADDED = 'POST_ADDED';

// The branch field of a book indicates which library has it in stock
const books = [
  {
    title: 'Harry Potter and the Chamber of Secrets',
    author: 'J.K. Rowling',
  },
  {
    title: 'Jurassic Park',
    author: 'Michael Crichton',
  },
];

let a = '';
let num = 0;
setInterval(
  () => {
    if (!a) return;
    return pubsub.publish(a, { postAdded: { title: a + (++num) } })
  }, 2000);

const resolvers = {
  Query: {
    books() {
      return books;
    },
    // args.status, args.logdebugid, ag
    // viewData: (parent, args, context, info) => {

    // }
  },
  Subscription: {
    postAdded: {
      // Additional event labels can be passed to asyncIterator creation
      subscribe: (parent, args, context, info) => {
 //       console.log(args);
        a = args.name
        return pubsub.asyncIterator([args.name])
      }
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError: (err) => {
    console.error(err);
    err.message = {
      message: err.message,
    };
    return err;
  },
  subscriptions: {
    onConnect: (connectionParams, webSocket, context) => {
      console.log(context)
      // ...
    },
    onDisconnect: (webSocket, context) => {
      console.log(context)

      // ...
    },
  },
});

const PORT = '5002'
module.exports = function (app) {
  server.applyMiddleware({ app })
  const httpServer = http.createServer(app.callback());
  server.installSubscriptionHandlers(httpServer);
  httpServer.listen(PORT, () => {
    console.log(`🚀 Server ready at http://localhost:${PORT}${server.graphqlPath}`)
    console.log(`🚀 Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
  })
};
